package com.youlu.campus.service.sms.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.common.utils.RedisKeyUtil;
import com.youlu.campus.entity.SmsTemplate;
import com.youlu.campus.service.sms.SmsTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class SmsTemplateServiceImpl implements SmsTemplateService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public SmsTemplate findBySmsTemplate(String tenantId, String sign, String type) {
        log.info(":>>> 开始查找短信模版:{},type:{}", sign, type);
        if (StringUtils.isBlank(sign) || StringUtils.isBlank(type)) {
            log.error(":>>> 查找短信模版参数错误");
            throw new BusinessException("查找短信模版参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("sign").is(sign).and("type").is(type));
        SmsTemplate smsTemplate = mongoTemplate.findOne(query, SmsTemplate.class);
        log.debug(":>>> 获取的短信模版信息为:{}", JSON.toJSONString(smsTemplate));
        return smsTemplate;
    }

    @Override
    public SmsTemplate findBySignAndType(String sign, String type) {
        if (StringUtils.isBlank(sign) || StringUtils.isBlank(type)) {
            log.error(":>>> 查找短信模版参数错误");
            return null;
        }
        String key = RedisKeyUtil.getSmsTemplateKey(sign, type);
        String json = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(json)) {
            SmsTemplate smsTemplate = JSON.parseObject(json, SmsTemplate.class);
            return smsTemplate;
        }
        Query query = new Query().addCriteria(Criteria.where("sign").is(sign).and("type").is(type));
        SmsTemplate smsTemplate = mongoTemplate.findOne(query, SmsTemplate.class);
        log.debug(":>>> 获取的短信模版信息为:{}", JSON.toJSONString(smsTemplate));
        redisTemplate.opsForValue().set(key, JSON.toJSONString(smsTemplate), 1, TimeUnit.HOURS);
        return smsTemplate;
    }

    @Override
    public SmsTemplate findByTemplateId(Integer templateId) {
        log.info(":>>> 开始查找短信模版,模版ID:{},", templateId);
        Query query = new Query().addCriteria(Criteria.where("tempalteId").is(templateId));
        SmsTemplate smsTemplate = mongoTemplate.findOne(query, SmsTemplate.class);
        log.debug(":>>> 获取的短信模版信息为:{}", JSON.toJSONString(smsTemplate));
        return smsTemplate;
    }
}
